/** @file    NetworkProtocolTcp.cpp
 *  @author  Alessandro Polo
 *  @version $Id: NetworkProtocolTcp.cpp 2856 2010-08-06 21:09:29Z alex $
 *  @brief
 * File containing methods for the wosh::network::NetworkProtocolTcp class.
 * The header for this class can be found in NetworkProtocolTcp.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include <framework/network/NetworkProtocolTcp.h>
 #include <core/ObjectFactory.h>
 #include <framework/network/NetworkUtilities.h>


using namespace std;
namespace wosh {
 namespace network {

 WOSH_REGISTER(wosh::network::NetworkProtocolTcp, "wosh::NetworkProtocol", 1.01, _static_NetworkProtocolTcp)

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS

NetworkProtocolTcp::NetworkProtocolTcp()
	: INetworkChannelTcpServerListener(), NetworkProtocol() {
	Object::setName( _NetworkProtocolTcp_NAME );
	Log.setContext( _NetworkProtocolTcp_NAME );

	Properties.set( _NetworkProtocol_KEY_ProtocolPrefix, _NetworkProtocolTcp_PREFIX );
	Properties.set( _NetworkProtocol_KEY_Priority, _NetworkProtocolTcp_Priority );
 }

NetworkProtocolTcp::~NetworkProtocolTcp() {
	stopListeningChannels();
	this->Servers.free();
 }

//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool NetworkProtocolTcp::supportProtocol( const std::string& protocol_string ) const {
	if ( protocol_string.size() < strlen(_NetworkProtocolTcp_PREFIX)+1 ) return false;
	if ( protocol_string.substr(0, strlen(_NetworkProtocolTcp_PREFIX)) != _NetworkProtocolTcp_PREFIX ) return false;
	return true;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT NetworkProtocolTcp::listenChannel( const std::string& protocol_string, unsigned long timeout ) {
	if ( !supportProtocol(protocol_string) ) return WRET_ERR_PARAM;
	std::string addressport = protocol_string.substr(6);
	wosh::network::NetworkChannelTcpServer* chs = new wosh::network::NetworkChannelTcpServer("NetworkChannelTcpServer#" + addressport);
	chs->setListener(this);
	WRESULT ret = chs->listen(addressport, timeout);
	if ( WFAILED(ret) ) {
		delete chs;
		return ret;
	 }
	this->Servers.append(chs);
	Properties.transactionBeginWrite();
	Properties.update( _NetworkProtocol_KEY_ServersCount, this->Servers.size() );
	Properties.transactionEnd();
	if ( this->listener != NULL )
		this->listener->network_protocol_supported(protocol_string, NULL, this);
	return ret;
 }

WRESULT NetworkProtocolTcp::stopListeningChannels( unsigned long timeout ) {
	this->Servers.transactionBeginWrite();
	tChannelTcpList::ConstIterator it;
	const tChannelTcpList::ConstIterator it_end = this->Servers.end();
	for ( it=this->Servers.begin(); it!=it_end; ++it ) {
		if ( *it == NULL || !(*it)->isListening() ) continue;
		(*it)->stopListening(timeout);
	 }
	this->Servers.transactionEnd();
	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT NetworkProtocolTcp::connectChannel( const std::string& protocol_string, unsigned long timeout ) {
	if ( !supportProtocol(protocol_string) ) return WRET_ERR_PARAM;
	std::string addressport = protocol_string.substr(6);
	NetworkChannelTcp* ch = new NetworkChannelTcp("NetworkChannelTcp#" + addressport);
	WRESULT ret = ch->connect(addressport, timeout);
	if ( this->listener != NULL )
		this->listener->network_protocol_new_channel(ch, 0, this);
	return ret;
 }

WRESULT NetworkProtocolTcp::connectChannel( const std::vector<std::string>& protocolsAvailable, unsigned long timeout ) {
	if ( protocolsAvailable.size() == 0 ) return WRET_ERR_PARAM;
	if ( protocolsAvailable.size() == 1 ) {
		return connectChannel( protocolsAvailable.at(0), timeout );
	 }
	std::vector<std::string> interfaces;
	NetworkUtilities::listAvailableInterfaces( interfaces );
	short bestRank = -1;
	short rank = 0;
	std::string bestProtocol = "";
	std::vector<std::string>::const_iterator it_p;
	std::vector<std::string>::const_iterator it_ips;
	for ( it_p=protocolsAvailable.begin(); it_p!=protocolsAvailable.end(); it_p++) {
		if ( !supportProtocol(*it_p) )
			continue;
		for ( it_ips=interfaces.begin(); it_ips!=interfaces.end(); it_ips++) {
			rank = wosh::network::NetworkUtilities::compareSubNet( it_p->substr(6), *it_ips );
			if ( rank <= bestRank ) continue;
			bestRank = rank;
			bestProtocol = *it_p;
		 }
	 }
	if ( bestProtocol.size() > 0 )
		return connectChannel( bestProtocol, timeout );
	return WRET_ERR_PARAM;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void NetworkProtocolTcp::channelTcpServer_incomingConnection( wosh::network::NetworkChannelTcpServer* , int socket_id ) {
	wosh::network::NetworkChannelTcp* ch = new wosh::network::NetworkChannelTcp("NetworkChannelTcp#" + Utilities::toString(socket_id) );
	ch->socket_id = socket_id;
	if ( this->listener != NULL )
		this->listener->network_protocol_new_channel(ch, 1, this);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace network
}; // namespace wosh
